package com.mazaiting.instructions.stores;

import com.mazaiting.instructions.base.Index8Instruction;
import com.mazaiting.instructions.base.NoOperandsInstruction;
import com.mazaiting.rtda.MtFrame;
import com.mazaiting.rtda.heap.MtObject;

/**
 * 变量从操作数栈顶弹出，然后存入局部变量表
 *
 * @author mazaiting
 * @since 2021/8/14
 */
public class AStoreInstruction {

    /**
     * 变量从操作数栈顶弹出，然后存入局部变量表
     * @param frame 栈帧
     * @param index 索引
     */
    private static void store(MtFrame frame, int index) {
        // 变量从操作数栈顶弹出
        MtObject ref = frame.getOperandStack().popRef();
        // 推入操作数栈顶
        frame.getLocalVars().setRef(index, ref);
    }

    public static class AStore extends Index8Instruction {
        @Override
        public void execute(MtFrame frame) {
            store(frame, index);
        }

        @Override
        public String toString() {
            return "astore " + index;
        }
    }

    public static class AStore0 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            store(frame, 0);
        }

        @Override
        public String toString() {
            return "astore_0";
        }
    }

    public static class AStore1 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            store(frame, 1);
        }

        @Override
        public String toString() {
            return "astore_1";
        }
    }

    public static class AStore2 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            store(frame, 2);
        }

        @Override
        public String toString() {
            return "astore_2";
        }
    }

    public static class AStore3 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            store(frame, 3);
        }

        @Override
        public String toString() {
            return "astore_3";
        }
    }

    public static class AStore4 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            store(frame, 4);
        }

        @Override
        public String toString() {
            return "astore_4";
        }
    }

}
